package com.eascs.workflow.controller;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.account.account.AccountEntity;
import com.eascs.admin.common.vo.O2oUpdateLoanExpireTimeEntity;
import com.eascs.admin.o2o.backFees.entity.O2oBackFeesEntity;
import com.eascs.admin.o2o.backFees.service.O2oBackFeesService;
import com.eascs.admin.o2o.backfee.entity.O2OComBackFee;
import com.eascs.admin.o2o.backfee.service.O2OComBankFeeService;
import com.eascs.admin.o2o.badloan.entity.O2oCacleEntity;
import com.eascs.admin.o2o.badloan.service.O2oCancleServiceImpl;
import com.eascs.admin.o2o.credit.entity.CreditReport;
import com.eascs.admin.o2o.credit.service.CreditReportService;
import com.eascs.admin.o2o.enterpriseZX.entity.O2oEnterpriseZxEntity;
import com.eascs.admin.o2o.enterpriseZX.service.O2oEnterpriseZxService;
import com.eascs.admin.o2o.finance.service.O2oFinanceFlowService;
import com.eascs.admin.o2o.internal.entity.AuditComments;
import com.eascs.admin.o2o.internal.entity.LoanapplyExpand;
import com.eascs.admin.o2o.internal.entity.LoanapplyExpandDetail;
import com.eascs.admin.o2o.internal.form.LoanapplyExpandForm;
import com.eascs.admin.o2o.internal.form.LoanapplyForm;
import com.eascs.admin.o2o.internal.service.AuditCommentService;
import com.eascs.admin.o2o.internal.service.LoanapplyExpandDetailService;
import com.eascs.admin.o2o.internal.service.LoanapplyExpandService;
import com.eascs.admin.o2o.internal.service.PayMentService;
import com.eascs.admin.o2o.internal.util.BaseUserUtil;
import com.eascs.admin.o2o.internal.util.BeanUtils;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.action.ContractAndBankInfoForm;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oChargeSituationService;
import com.eascs.admin.o2o.loan.service.O2oLoanUserService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.o2o.loan.utils.BankRate;
import com.eascs.admin.o2o.loanAccount.entity.O2oCollectFee;
import com.eascs.admin.o2o.loanAccount.service.IO2oCollectFeesService;
import com.eascs.admin.o2o.loanAccount.vo.O2oCollectFeesVo;
import com.eascs.admin.o2o.o2ozx.serviceimpl.O2oLoadUserZxServiceImpl;
import com.eascs.admin.o2o.o2ozx.serviceimpl.O2oZxServiceImpl;
import com.eascs.admin.o2o.specialInterview.entity.O2OSpecialInterview;
import com.eascs.admin.o2o.specialInterview.service.O2OSpecialInterviewService;
import com.eascs.admin.o2o.zx.entity.O2oLoanUserEntityZx;
import com.eascs.admin.o2o.zx.entity.O2oZxEntity;
import com.eascs.admin.recordlog.constant.O2oLogType;
import com.eascs.admin.recordlog.servcie.O2oRecordLogService;
import com.eascs.afterloan.entity.AdvancedPayment;
import com.eascs.afterloan.form.AdvanceSettleForm;
import com.eascs.afterloan.service.AdvanceSettleService;
import com.eascs.afterloan.service.DeclareSignService;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.datalist.entity.O2oDataListEntity;
import com.eascs.datalist.service.O2oDataListService;
import com.eascs.file.FileTypeConstants;
import com.eascs.loan.form.O2oLoanForm;
import com.eascs.loan.service.impl.O2oLoanServiceImpl;
import com.eascs.overdue.entity.O2oStatus;
import com.eascs.overdue.service.O2oOverdueReportService;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.common.vo.CancleProcessParam;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.form.CreditForm;
import com.eascs.workflow.form.MQFrom;
import com.eascs.workflow.form.MQSCForm;
import com.eascs.workflow.form.MQZBSBYHFrom;
import com.eascs.workflow.form.O2OZXZBQRForm;
import com.eascs.workflow.form.SDEntity;
import com.eascs.workflow.form.SDForm;
import com.eascs.workflow.form.SQBZJForm;
import com.eascs.workflow.form.TFBZJForm;
import com.eascs.workflow.form.YHSSForm;
import com.eascs.workflow.form.ZXSSYHForm;
import com.eascs.workflow.service.LoanapplyExpandUpdateService;
import com.eascs.workflow.service.WorkFlowSumbitService;
import com.eascs.workflow.util.CreditTransforCreditFrom;
import com.eascs.workflow.util.TranferResult;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 所有动态表单提交类
 * 
 * @author ycz
 *
 */
@RestController
@RequestMapping("/workflowsubmit")
public class WorkFlowSubmitController extends BaseRestController {
	private static Logger logger = LoggerFactory.getLogger(WorkFlowSubmitController.class);
	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;
	@Autowired
	private O2oRecordLogService o2oRecordLogService;
	@Autowired
	private PayMentService payMentService;
	@Autowired
	private LoanapplyExpandService loanapplyExpandService;
	@Autowired
	private BaseUserUtil userUtil;
	@Reference
	WorkFlowService workFlowService;
	@Autowired
	private O2oLoanUserService o2oLoanUserService;
	@Autowired
	private WorkFlowSumbitService workFlowSumbitService;
	@Autowired
	private CreditReportService creditReportService;
	@Autowired
	private O2OComBankFeeService o2oComBankFeeService;
	@Autowired
	private LoanapplyExpandUpdateService loanapplyExpandUpdateService;
	@Autowired
	private O2oOverdueReportService o2oOverdueReportService;
	@Autowired
	private AuditCommentService auditCommentService;
	@Autowired
	private LoanapplyExpandDetailService loanapplyExpandDetailService;
	@Autowired
	AdvanceSettleService advanceSettleService;
	@Autowired
	O2OSpecialInterviewService o2OSpecialInterviewService;

	@Autowired
	private O2oDataListService o2oDataListService;

	@Autowired
	private O2oEnterpriseZxService o2oEnterpriseZxService;

	@Autowired
	O2oBackFeesService o2oBackFeesService;

	@Autowired
	private O2oZxServiceImpl o2oZxServiceImpl;
	@Autowired
	private O2oLoadUserZxServiceImpl o2oLoadUserZxServiceImpl;

	@Autowired
	IO2oCollectFeesService io2oCollectFeesService;
	@Autowired
	DeclareSignService declareSignService;
	@Autowired
	O2oLoanServiceImpl o2oLoanServiceImpl;

	@Autowired
	O2oChargeSituationService o2oChargeSituationService;

	/**
	 * 征信 财务审核表单 提交
	 * 
	 * @param zXPTCWForm
	 * @return
	 */
	@RequestMapping(value = "/zx_ptcw")
	public BaseRestResult<String> ptcwlist(SDForm sdForm) {
		BigDecimal flag = new BigDecimal(0);
		if (sdForm.getTakeAvgAmount().compareTo(flag) == -1 || sdForm.getPaymentAvgAmount().compareTo(flag) == -1) {
			if (!StringUtils.isNotBlank(sdForm.getZxRemark())) {
				return BaseRestResult.warn("月平均包含负数,请对特殊说明进行描述");
			}
		}
		SDEntity sd = new SDEntity();
		sdForm.setUpdateTime(new Date());
		BeanUtils.copyProperties(sdForm, sd);
		workFlowSumbitService.updateZxPTCW(sdForm, sd);
		return BaseRestResult.warn("保存成功");
	}

	/**
	 * 征信 送审银行
	 * 
	 * @param zXSSYHForm
	 * @return
	 */
	@RequestMapping(value = "/zx_form")
	public BaseRestResult<String> approval(ZXSSYHForm zXSSYHForm) {
		O2oLoanapplyEntity loanEntity = o2oLoanapplyService.findById(zXSSYHForm.getReferId());
		loanEntity.setBankType(zXSSYHForm.getBanktype());
		if (StatusContexts.LOAN_TYPE_BK.equals(loanEntity.getLoanType()) || StatusContexts.LOAN_TYPE_BP.equals(loanEntity.getLoanType()) || StatusContexts.LOAN_TYPE_SG.equals(loanEntity.getLoanType()) || StatusContexts.LOAN_TYPE_YC.equals(loanEntity.getLoanType()) || StatusContexts.LOAN_TYPE_SC.equals(loanEntity.getLoanType())) {
			if (zXSSYHForm.getBanktype().equals(BankRate.BANK_BC)) {
				loanEntity.setLoanrate(BankRate.BANK_BC_RATE);
			} else if (zXSSYHForm.getBanktype().equals(BankRate.BANK_CBC)) {
				loanEntity.setLoanrate(BankRate.BANK_CBC_RATE);
			} else if (zXSSYHForm.getBanktype().equals(BankRate.BANK_GACZ)) {
				loanEntity.setLoanrate(BankRate.BANK_GACZ_RATE);
			} else if (zXSSYHForm.getBanktype().equals(BankRate.BANK_CCBHN)) {
				loanEntity.setLoanrate(BankRate.BANK_CCBHN_RATE);
			} else if (zXSSYHForm.getBanktype().equals(BankRate.BANK_QLB)) {
				loanEntity.setLoanrate(BankRate.BANK_QLB_RATE);
			} else if (zXSSYHForm.getBanktype().equals(BankRate.BANK_CIBJN)) {
				loanEntity.setLoanrate(BankRate.BANK_CIBJN_RATE);
			} else if (zXSSYHForm.getBanktype().equals(BankRate.BANK_JCB)) {
				loanEntity.setLoanrate(BankRate.BANK_JCB_RATE);
			} else if (zXSSYHForm.getBanktype().equals(BankRate.BANK_ZZB)) {
				loanEntity.setLoanrate(BankRate.BANK_ZZB_RATE);
			} else if (zXSSYHForm.getBanktype().equals(BankRate.BANK_SPDBGZ)) {
				loanEntity.setLoanrate(BankRate.BANK_SPDBGZ_RATE);
			} else if (zXSSYHForm.getBanktype().equals(BankRate.BANK_SXB)) {
				loanEntity.setLoanrate(BankRate.BANK_SXB_RATE);
			} else if (zXSSYHForm.getBanktype().equals(BankRate.BANK_ZLB)) {
				loanEntity.setLoanrate(BankRate.BANK_ZLB_RATE);
			} else if (zXSSYHForm.getBanktype().equals(BankRate.BANK_SPDBJN)) {
				loanEntity.setLoanrate(BankRate.BANK_SPDBJN_RATE);
			} else {
				loanEntity.setLoanrate(BankRate.BANK_OTH_RATE);
			}
		}
		logger.info("银行利率：", loanEntity.getLoanrate());
		o2oLoanapplyService.updateEntityById(loanEntity);
		return BaseRestResult.warn("操作成功");
	}

	/**
	 * 新征信 总部征信确认
	 * 
	 * @param zXSSYHForm
	 * @return
	 */
	@RequestMapping(value = "/o2ozx_form")
	public BaseRestResult<String> o2ozxForm(O2OZXZBQRForm o2OZXZBQRForm) {
		O2oZxEntity o2oZxEntity = o2oZxServiceImpl.getEntityById(o2OZXZBQRForm.getReferId());

		if (o2OZXZBQRForm.getZxDate() == null) {
			return BaseRestResult.warn("请填客户征信报告时间");
		}

		List<O2oDataListEntity> dataList = o2oDataListService.findByEntityList(o2OZXZBQRForm.getReferId());
		O2oDataListEntity ZXBGDATAEntity = null;
		for (int i = 0; i < dataList.size(); i++) {
			O2oDataListEntity entity = dataList.get(i);
			if (entity.getDatalistCode().equals(FileTypeConstants.DALIST_TYPE_ZXBGDATA)) {
				ZXBGDATAEntity = entity;
			}
		}
		if (ZXBGDATAEntity == null) {
			return BaseRestResult.warn("请上传客户征信报告");
		}

		O2oLoanUserEntityZx o2oLoanUserEntityZx = o2oLoadUserZxServiceImpl.getEntityByZxNo(o2OZXZBQRForm.getReferId());
		if (o2OZXZBQRForm.getZxDate() != null) {
			o2oLoanUserEntityZx.setZxDate(o2OZXZBQRForm.getZxDate());
		}
		if (o2OZXZBQRForm.getZxTdDate() != null) {
			o2oLoanUserEntityZx.setZxTdDate(o2OZXZBQRForm.getZxTdDate());
		}
		o2oZxServiceImpl.update(o2oZxEntity);

		o2oLoadUserZxServiceImpl.update(o2oLoanUserEntityZx);

		return BaseRestResult.warn("操作成功");
	}

	/**
	 * 企业征信 总部征信确认
	 * 
	 * @param zXSSYHForm
	 * @return
	 */
	@RequestMapping(value = "/o2oQYzx_form")
	public BaseRestResult<String> o2oQYzxForm(O2OZXZBQRForm o2OZXZBQRForm) {

		O2oEnterpriseZxEntity o2oEnterpriseZxEntity = o2oEnterpriseZxService.getEntityById(o2OZXZBQRForm.getReferId());

		if (o2OZXZBQRForm.getZxDate() == null) {
			return BaseRestResult.warn("请填写企业征信报告时间");
		}

		List<O2oDataListEntity> dataList = o2oDataListService.findByEntityList(o2OZXZBQRForm.getReferId());
		O2oDataListEntity ZXBGDATAEntity = null;
		for (int i = 0; i < dataList.size(); i++) {
			O2oDataListEntity entity = dataList.get(i);
			if (entity.getDatalistCode().equals(FileTypeConstants.ENTERPRISE_ZX_IDCARD)) {
				ZXBGDATAEntity = entity;
			}
		}
		if (ZXBGDATAEntity == null) {
			return BaseRestResult.warn("请上传企业征信报告");
		}

		if (o2OZXZBQRForm.getZxDate() != null) {
			o2oEnterpriseZxEntity.setZxTime(o2OZXZBQRForm.getZxDate());
		}
		o2oEnterpriseZxService.update(o2oEnterpriseZxEntity);
		return BaseRestResult.warn("操作成功");
	}

	/**
	 * @Title: approval_tqhk
	 * @Description: 提前还款结清-更新结清日期
	 * @author 张庆奇
	 * @param advanceSettleForm
	 * @return
	 * @throws ParseException
	 * @return BaseRestResult<String>
	 * @throws @date 2017年2月21日 下午1:29:44
	 */
	@RequestMapping(value = "/tqhk_form")
	public BaseRestResult<String> approval_tqhk(AdvanceSettleForm advanceSettleForm) throws ParseException {
		if (advanceSettleForm.getSettleDate() == null) {
			return BaseRestResult.warn("结清日期不能为空！");
		}
		AdvancedPayment advancedPayment = advanceSettleService.queryEntity(advanceSettleForm.getReferId(), null);
		advancedPayment.setSettleDate(DateUtils.parseDate(advanceSettleForm.getSettleDate(), new String[] { "yyyy-MM-dd" }));
		advanceSettleService.updateById(advancedPayment);
		return BaseRestResult.warn("操作成功");
	}

	/**
	 * 征信总部初审 保存征信情况
	 * 
	 * @param creditForm
	 * @return
	 */
	@RequestMapping(value = "/credit_form")
	public BaseRestResult<String> updateCredit(CreditForm creditForm) {
		CreditReport creditReport = new CreditReport();
		if (!StringUtils.isNotBlank(creditForm.getId())) {
			CreditTransforCreditFrom.saveCreditReport(creditReport, creditForm);
			creditReport.setCreator(userUtil.getCreateOr());
			creditReport.setUpdator(userUtil.getCreateOr());
			creditReport.setFlag(StatusContexts.O2O_YES);
			creditReportService.saveEntity(creditReport);
			if (StringUtils.isNotBlank(creditForm.getFlag()) && ("1").equals(creditForm.getFlag())) {
				CreditReport materCreditReport = new CreditReport();
				CreditTransforCreditFrom.saveSpouseCreditReport(materCreditReport, creditForm);
				materCreditReport.setLoanapplyNo(creditForm.getLoanapplyNo());
				materCreditReport.setParentId(creditReport.getId());
				materCreditReport.setCreator(userUtil.getCreateOr());
				materCreditReport.setUpdator(userUtil.getCreateOr());
				CreditTransforCreditFrom.saveSpouseCreditReport(materCreditReport, creditForm);
				creditReportService.saveEntity(materCreditReport);
			}
		} else {
			CreditReport creditReport1 = creditReportService.getById(creditForm.getId());
			Date date = new Date();
			creditReport.setCreateTime(creditReport1.getCreateTime());
			creditReport.setCreator(creditReport1.getCreator());
			creditReport.setUpdator(userUtil.getUpdateOr());
			creditReport.setUpdateTime(date);
			creditReport.setLoanapplyNo(creditReport1.getLoanapplyNo());
			creditReport.setFlag(StatusContexts.O2O_YES);
			creditReport.setParentId(creditReport1.getParentId());
			CreditTransforCreditFrom.updateCreditReport(creditReport, creditForm);
			creditReportService.updateEntity(creditReport);
			if (StringUtils.isNotBlank(creditForm.getFlag()) && ("1").equals(creditForm.getFlag())) {
				if (StringUtils.isNotBlank(creditForm.getIds())) {
					CreditReport materCreditReport = new CreditReport();
					CreditTransforCreditFrom.CreditFromTransToCredit(materCreditReport, creditForm);
					materCreditReport.setLoanapplyNo(creditReport1.getLoanapplyNo());
					materCreditReport.setParentId(creditReport1.getId());
					materCreditReport.setId(creditForm.getIds());
					materCreditReport.setUpdator(userUtil.getUpdateOr());
					materCreditReport.setUpdateTime(date);
					materCreditReport.setCreateTime(creditReport1.getCreateTime());
					materCreditReport.setCreator(creditReport1.getCreator());
					materCreditReport.setFlag(StatusContexts.O2O_YES);
					creditReportService.updateEntity(materCreditReport);
				} else {
					CreditReport materCreditReport = new CreditReport();
					CreditTransforCreditFrom.saveSpouseCreditReport(materCreditReport, creditForm);
					materCreditReport.setLoanapplyNo(creditForm.getLoanapplyNo());
					materCreditReport.setParentId(creditReport.getId());
					materCreditReport.setCreator(userUtil.getCreateOr());
					materCreditReport.setUpdator(userUtil.getCreateOr());
					CreditTransforCreditFrom.saveSpouseCreditReport(materCreditReport, creditForm);
					creditReportService.saveEntity(materCreditReport);
				}
			}
		}
		return BaseRestResult.info("保存成功").andCloseActionDialog().andJquerySelectAjaxAction("#file_uploader");
	}

	/**
	 * 保存内审动态表单
	 * 
	 * @param payform
	 * @return
	 */
	@RequestMapping("/save_ns")
	public BaseRestResult<String> save(LoanapplyForm loanapplyForm) {
		logger.info("保存内审动态表单:" + loanapplyForm.toString());
		O2oLoanapplyEntity loanapply = o2oLoanapplyService.findById(loanapplyForm.getLoanapplyNo());
		/*
		 * if (StringUtils.isNotBlank(loanapplyForm.getNodeCode()) &&
		 * "NS_XDJL".equals(loanapplyForm.getNodeCode())) { if
		 * (!StringUtils.isNotBlank(loanapplyForm.getBuybackId()) &&
		 * !StringUtils.isNotBlank(loanapplyForm.getBuybackName())) { return
		 * BaseRestResult.warn("回购担保方不能为空"); } else { OaUnit oaUnit =
		 * oaLoanapplyDetailService.findUnit(loanapplyForm.getBuybackId().trim()
		 * ); loanapplyForm.setBuybackCode(oaUnit.getUnitCode()); } } else {
		 * loanapplyForm.setBuybackId(loanapply.getBuybackId());
		 * loanapplyForm.setBuybackCode(loanapply.getBuybackCode());
		 * loanapplyForm.setBuybackName(loanapply.getBuybackName()); }
		 */
		if (loanapplyForm.getRisk().doubleValue() < 0) {
			return BaseRestResult.warn("风险补偿金不能小于0");
		}
		if (loanapplyForm.getEaMount().compareTo(new BigDecimal(1000000.00)) == 1) {
			return BaseRestResult.warn("EA批复金额不能大于100万");
		}
		if (StatusContexts.LOAN_TYPE_BK.equals(loanapply.getLoanType()) || StatusContexts.LOAN_TYPE_BP.equals(loanapply.getLoanType()) || StatusContexts.LOAN_TYPE_BP_JX.equals(loanapply.getLoanType()) || StatusContexts.LOAN_TYPE_SG.equals(loanapply.getLoanType()) || StatusContexts.LOAN_TYPE_YC.equals(loanapply.getLoanType()) || StatusContexts.LOAN_TYPE_SC.equals(loanapply.getLoanType())) {
			if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_BC)) {
				loanapplyForm.setLoanrate(BankRate.BANK_BC_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_CBC)) {
				loanapplyForm.setLoanrate(BankRate.BANK_CBC_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_GACZ)) {
				loanapplyForm.setLoanrate(BankRate.BANK_GACZ_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_CCBHN)) {
				loanapplyForm.setLoanrate(BankRate.BANK_CCBHN_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_QLB)) {
				loanapplyForm.setLoanrate(BankRate.BANK_QLB_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_CIBJN)) {
				loanapplyForm.setLoanrate(BankRate.BANK_CIBJN_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_JCB)) {
				loanapplyForm.setLoanrate(BankRate.BANK_JCB_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_ZZB)) {
				loanapplyForm.setLoanrate(BankRate.BANK_ZZB_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_SPDBGZ)) {
				loanapplyForm.setLoanrate(BankRate.BANK_SPDBGZ_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_SXB)) {
				loanapplyForm.setLoanrate(BankRate.BANK_SXB_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_ZLB)) {
				loanapplyForm.setLoanrate(BankRate.BANK_ZLB_RATE);
			}else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_SPDBJN)) {
				loanapplyForm.setLoanrate(BankRate.BANK_SPDBJN_RATE);
			} else {
				loanapplyForm.setLoanrate(BankRate.BANK_OTH_RATE);
			}
			if (!StringUtils.isNotEmpty(loanapplyForm.getRemark())) {
				List<AuditComments> auditComments = auditCommentService.findAuditsList(loanapplyForm.getLoanapplyNo());
				if (auditComments != null && !auditComments.isEmpty()) {
					AuditComments auditComment = auditComments.get(0);
					BigDecimal rate = new BigDecimal(100);
					if (loanapplyForm.getGeneralRate().compareTo(auditComment.getGeneralRate()) != 0) {
						return BaseRestResult.warn("上次综合费率：" + com.eascs.admin.common.utils.StringUtils.bdFormat(auditComment.getGeneralRate().multiply(rate), 4) + "%与本次修改综合费率：" + com.eascs.admin.common.utils.StringUtils.bdFormat(loanapplyForm.getGeneralRate().multiply(rate), 4) + "%,请填写备注");
					}
					if (loanapplyForm.getDepositrate().compareTo(auditComment.getDepositrate()) != 0) {
						return BaseRestResult.warn("上次保证金费率：" + com.eascs.admin.common.utils.StringUtils.bdFormat(auditComment.getDepositrate().multiply(rate), 3) + "%与本次保证金费率：" + com.eascs.admin.common.utils.StringUtils.bdFormat(loanapplyForm.getDepositrate().multiply(rate), 3) + "%,请填写备注");
					}
					if (loanapplyForm.getManagefeerate().compareTo(auditComment.getManagefeerate()) != 0) {
						return BaseRestResult.warn("上次管理费费率：" + com.eascs.admin.common.utils.StringUtils.bdFormat(auditComment.getManagefeerate().multiply(rate), 3) + "%与本次管理费费率：" + com.eascs.admin.common.utils.StringUtils.bdFormat(loanapplyForm.getManagefeerate().multiply(rate), 3) + "%,请填写备注");
					}
					if (loanapplyForm.getRisk().compareTo(auditComment.getRisk()) != 0) {
						return BaseRestResult.warn("上次风险补偿金费率：" + com.eascs.admin.common.utils.StringUtils.bdFormat(auditComment.getRisk().multiply(rate), 4) + "%与本次风险补偿金费率：" + com.eascs.admin.common.utils.StringUtils.bdFormat(loanapplyForm.getRisk().multiply(rate), 4) + "%,请填写备注");
					}
				}
			}
			payMentService.bKloan(loanapplyForm, loanapply);
		} else if (StatusContexts.LOAN_TYPE_EA.equals(loanapply.getLoanType())) {
			payMentService.eAloan(loanapplyForm, loanapply);
		} else {
			payMentService.fQloan(loanapplyForm, loanapply);
		}
		return BaseRestResult.warn("保存成功");
	}

	/**
	 * 新建状态下,编辑内审信息,保存内审动态表单
	 * 
	 * @param payform
	 * @return
	 */
	@RequestMapping("/saveNS")
	public BaseRestResult<String> saveNS(LoanapplyForm loanapplyForm) {
		logger.info("保存内审动态表单:" + loanapplyForm.toString());
		O2oLoanapplyEntity loanapply = o2oLoanapplyService.findById(loanapplyForm.getLoanapplyNo());
		O2oLoanUserEntity user = o2oLoanapplyService.findLoanUserEntity(loanapply.getLoanapplyNo(), loanapply.getLoanId());
		O2oLoanUserEntity mateUser = o2oLoanUserService.findSpouseId(loanapply.getLoanId(), loanapply.getLoanapplyNo());
		O2oZxEntity o2oZxEntity = o2oZxServiceImpl.getEntityById(user.getZxNo());
		if (!o2oZxEntity.getZxBank().equals("BC")) {

			if (loanapplyForm.getBankLoanName().equals("BC")) {

				return BaseRestResult.warn("贷款单借款人关联的是非中国银行的征信报告，送审银行不能选择中行");

			}

		}

		if (mateUser != null && StringUtils.isNotBlank(mateUser.getZxNo())) {
			O2oZxEntity mateZxEntity = o2oZxServiceImpl.getEntityById(mateUser.getZxNo());
			if (!mateZxEntity.getZxBank().equals("BC")) {

				if (loanapplyForm.getBankLoanName().equals("BC")) {

					return BaseRestResult.warn("贷款单配偶关联的是非中国银行的征信报告，送审银行不能选择中行");

				}

			}

		}
		/*
		 * if (StringUtils.isNotBlank(loanapplyForm.getNodeCode()) &&
		 * "NS_XDJL".equals(loanapplyForm.getNodeCode())) { if
		 * (!StringUtils.isNotBlank(loanapplyForm.getBuybackId()) &&
		 * !StringUtils.isNotBlank(loanapplyForm.getBuybackName())) { return
		 * BaseRestResult.warn("回购担保方不能为空"); } else { OaUnit oaUnit =
		 * oaLoanapplyDetailService.findUnit(loanapplyForm.getBuybackId().trim()
		 * ); loanapplyForm.setBuybackCode(oaUnit.getUnitCode()); } } else {
		 * loanapplyForm.setBuybackId(loanapply.getBuybackId());
		 * loanapplyForm.setBuybackCode(loanapply.getBuybackCode());
		 * loanapplyForm.setBuybackName(loanapply.getBuybackName()); }
		 */
		if (loanapplyForm.getRisk().doubleValue() < 0) {
			return BaseRestResult.warn("风险补偿金不能小于0");
		}
		if (loanapplyForm.getEaMount().compareTo(new BigDecimal(1000000.00)) == 1) {
			return BaseRestResult.warn("EA批复金额不能大于100万");
		}
		if (StringUtil.isBlank(loanapplyForm.getRepayMentway())) {
			return BaseRestResult.warn("还款方式不能为空");
		}
		if (StringUtil.isBlank(loanapplyForm.getGuarAnteeWay())) {
			return BaseRestResult.warn("担保方式不能为空");
		}
		logger.info("内部推荐人={}", loanapplyForm.getReferrerNo());
//		if (StringUtil.isBlank(loanapplyForm.getReferrerNo())) {
//			return BaseRestResult.warn("内部推荐人不能为空");
//		}
		if (StatusContexts.LOAN_TYPE_BK.equals(loanapply.getLoanType()) || StatusContexts.LOAN_TYPE_BP.equals(loanapply.getLoanType()) || StatusContexts.LOAN_TYPE_BP_JX.equals(loanapply.getLoanType()) || StatusContexts.LOAN_TYPE_SG.equals(loanapply.getLoanType()) || StatusContexts.LOAN_TYPE_YC.equals(loanapply.getLoanType()) || StatusContexts.LOAN_TYPE_SC.equals(loanapply.getLoanType())) {
			if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_BC)) {
				loanapplyForm.setLoanrate(BankRate.BANK_BC_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_CBC)) {
				loanapplyForm.setLoanrate(BankRate.BANK_CBC_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_GACZ)) {
				loanapplyForm.setLoanrate(BankRate.BANK_GACZ_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_CCBHN)) {
				loanapplyForm.setLoanrate(BankRate.BANK_CCBHN_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_QLB)) {
				loanapplyForm.setLoanrate(BankRate.BANK_QLB_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_CIBJN)) {
				loanapplyForm.setLoanrate(BankRate.BANK_CIBJN_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_JCB)) {
				loanapplyForm.setLoanrate(BankRate.BANK_JCB_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_ZZB)) {
				loanapplyForm.setLoanrate(BankRate.BANK_ZZB_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_SPDBGZ)) {
				loanapplyForm.setLoanrate(BankRate.BANK_SPDBGZ_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_SXB)) {
				loanapplyForm.setLoanrate(BankRate.BANK_SXB_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_ZLB)) {
				loanapplyForm.setLoanrate(BankRate.BANK_ZLB_RATE);
			} else if (loanapplyForm.getBankLoanName().equals(BankRate.BANK_SPDBJN)) {
				loanapplyForm.setLoanrate(BankRate.BANK_SPDBJN_RATE);
			} else {
				loanapplyForm.setLoanrate(BankRate.BANK_OTH_RATE);
			}
			if (!StringUtils.isNotEmpty(loanapplyForm.getRemark())) {
				List<AuditComments> auditComments = auditCommentService.findAuditsList(loanapplyForm.getLoanapplyNo());
				if (auditComments != null && !auditComments.isEmpty()) {
					AuditComments auditComment = auditComments.get(0);
					BigDecimal rate = new BigDecimal(100);
					if (loanapplyForm.getGeneralRate().compareTo(auditComment.getGeneralRate()) != 0) {
						return BaseRestResult.warn("上次综合费率：" + com.eascs.admin.common.utils.StringUtils.bdFormat(auditComment.getGeneralRate().multiply(rate), 4) + "%与本次修改综合费率：" + com.eascs.admin.common.utils.StringUtils.bdFormat(loanapplyForm.getGeneralRate().multiply(rate), 4) + "%,请填写备注");
					}
					if (loanapplyForm.getDepositrate().compareTo(auditComment.getDepositrate()) != 0) {
						return BaseRestResult.warn("上次保证金费率：" + com.eascs.admin.common.utils.StringUtils.bdFormat(auditComment.getDepositrate().multiply(rate), 3) + "%与本次保证金费率：" + com.eascs.admin.common.utils.StringUtils.bdFormat(loanapplyForm.getDepositrate().multiply(rate), 3) + "%,请填写备注");
					}
					if (loanapplyForm.getManagefeerate().compareTo(auditComment.getManagefeerate()) != 0) {
						return BaseRestResult.warn("上次管理费费率：" + com.eascs.admin.common.utils.StringUtils.bdFormat(auditComment.getManagefeerate().multiply(rate), 3) + "%与本次管理费费率：" + com.eascs.admin.common.utils.StringUtils.bdFormat(loanapplyForm.getManagefeerate().multiply(rate), 3) + "%,请填写备注");
					}
					if (loanapplyForm.getRisk().compareTo(auditComment.getRisk()) != 0) {
						return BaseRestResult.warn("上次风险补偿金费率：" + com.eascs.admin.common.utils.StringUtils.bdFormat(auditComment.getRisk().multiply(rate), 4) + "%与本次风险补偿金费率：" + com.eascs.admin.common.utils.StringUtils.bdFormat(loanapplyForm.getRisk().multiply(rate), 4) + "%,请填写备注");
					}
				}
			}
			payMentService.bKloan_ns(loanapplyForm, loanapply);
		} else if (StatusContexts.LOAN_TYPE_EA.equals(loanapply.getLoanType())) {
			payMentService.eAloan_ns(loanapplyForm, loanapply);
		} else {
			payMentService.fQloan_ns(loanapplyForm, loanapply);
		}
		return BaseRestResult.warn("保存成功");
	}

	// /**
	// * 收取保证金和管理费 信贷经理提交
	// *
	// * @return
	// */
	// @RequestMapping("/saveManger")
	// public BaseRestResult<String> saveMangerDepsite(LoanapplyExpandForm
	// loanapplyExpandForm) {
	// LoanapplyExpand loanapplyExpand =
	// loanapplyExpandService.queryLoanapplyNo(loanapplyExpandForm.getLoanapplyNo());
	// if (loanapplyExpandForm.getTransferNums() != null &&
	// !loanapplyExpandForm.getTransferNums().isEmpty()) {
	// for (int i = 0; i < loanapplyExpandForm.getTransferNums().size(); i++) {
	// LoanapplyExpandDetail loanapplyExpandDetail =
	// loanapplyExpandDetailService.queryDetail(loanapplyExpand.getId());
	// loanapplyExpandForm.setTransferNum(loanapplyExpandForm.getTransferNums().get(i));
	// O2oLoanapplyEntity loanapply =
	// o2oLoanapplyService.findBillCode(loanapplyExpandForm.getTransferNum());
	// OaLoanapply oaloanapply =
	// oaLoanapplyService.queryBillCode(loanapplyExpandForm.getTransferNum());
	// if (null == loanapply && null == oaloanapply) {
	// return BaseRestResult.warn("划拨单号:" + loanapplyExpandForm.getTransferNum()
	// + "不存在,请核实");
	// } else {
	// if (oaloanapply != null && loanapply == null) {
	// O2oLoanapplyEntity o2oloanapply =
	// o2oLoanapplyService.findById(loanapplyExpandForm.getLoanapplyNo());
	// if (null != oaloanapply.getBillStatusInform() &&
	// !StatusContexts.BZJ_STATUS_CLO.equals(oaloanapply.getBillStatusInform()))
	// {
	// return BaseRestResult.warn("划拨单号:" + loanapplyExpandForm.getTransferNum()
	// + ",未完成收取保证金流程");
	// }
	// if (!checkDeposit(oaloanapply.getExistdeposit(),
	// oaloanapply.getUndeposit(), loanapplyExpandForm.getTransferDeposit())) {
	// return BaseRestResult.warn("划拨单号:" + loanapplyExpandForm.getTransferNum()
	// + ",划拨金额超过原单号可退保证金金额");
	// }
	// O2oLoanUserEntity loanUser =
	// o2oLoanUserService.findById(o2oloanapply.getLoanId(),
	// o2oloanapply.getLoanapplyNo());
	// int a =
	// oaLoanapplyService.isNotExistLoanUser(oaloanapply.getLoanapplyNo(),
	// loanUser.getUserFullName(), loanUser.getDocumentNo());
	// if (a <= 0) {
	// return BaseRestResult.warn("划拨单号:" + loanapplyExpandForm.getTransferNum()
	// + ",当前借款人身份证和姓名,与上笔贷款借款人姓名和身份证不匹配");
	// }
	// OaStatus oaStatus =
	// oaLoanapplyService.queryBackDeposit(loanapplyExpandForm.getTransferNum());
	// if (null != oaStatus &&
	// !oaStatus.getBillStatus().equals(StatusContexts.BZJ_STATUS_CLO)) {
	// return BaseRestResult.warn("划拨单号:" + loanapplyExpandForm.getTransferNum()
	// + ",正在老系统走退费流程");
	// }
	// List<O2oStatus> o2oStatusList =
	// oaLoanapplyService.findOverdueBillCode(loanapplyExpandForm.getTransferNum());
	// if (!o2oStatusList.isEmpty()) {
	// List<String> strList = new ArrayList<>();
	// for (int j = 0; j < o2oStatusList.size(); j++) {
	// strList.add(o2oStatusList.get(j).getStatus());
	// }
	// if (!strList.contains(StatusContexts.O2O_FIVE)) {
	// return BaseRestResult.warn("划拨单号:" + loanapplyExpandForm.getTransferNum()
	// + ",借款逾期未结清");
	// }
	// }
	// loanapplyExpandForm.setTransferDeposit(BigDecimalToZero(oaloanapply.getExistdeposit().subtract(BigDecimalToZero(oaloanapply.getUndeposit()))));
	// loanapplyExpandForm.setTrandepositNo(recSubretnAmount(oaloanapply.getExistdeposit(),
	// oaloanapply.getUndeposit()));
	// if (loanapplyExpandDetail != null) {
	// loanapplyExpandDetailService.updateExpandId(this.updateExpandDetail(loanapplyExpandDetail,
	// loanapplyExpand, loanapplyExpandForm));
	// } else {
	// loanapplyExpandForm.setReceiveDeposit(subBigDecimal(loanapplyExpand.getRecDeposite(),
	// loanapplyExpandForm.getTransferDeposit()));
	// loanapplyExpandDetailService.save(this.saveExpandDetail(loanapplyExpand,
	// loanapplyExpandForm));
	// }
	// } else if (oaloanapply == null && loanapply != null) {
	// LoanapplyExpand loanapplyEx =
	// loanapplyExpandService.fingByBillCode(loanapplyExpandForm.getTransferNum());
	// if (!loanapplyEx.getBillStatus().equals(StatusContexts.BZJ_STATUS_CLO)) {
	// return BaseRestResult.warn("划拨单号:" + loanapplyExpandForm.getTransferNum()
	// + "未收取保证金与管理费");
	// }
	// if (!checkDeposit(loanapplyEx.getRedDeposite(),
	// loanapplyEx.getRetaDeposite(), loanapplyExpandForm.getTransferDeposit()))
	// {
	// return BaseRestResult.warn("划拨单号:" + loanapplyExpandForm.getTransferNum()
	// + ",划拨金额超过原单号可退保证金金额");
	// }
	// O2oLoanapplyEntity oldLoanapply =
	// o2oLoanapplyService.findById(loanapplyEx.getLoanapply_no());
	// O2oLoanapplyEntity newLoanapply =
	// o2oLoanapplyService.findById(loanapplyExpandForm.getLoanapplyNo());
	// O2oLoanUserEntity oldLoanUser =
	// o2oLoanUserService.findById(oldLoanapply.getLoanId(),
	// oldLoanapply.getLoanapplyNo());
	// O2oLoanUserEntity newLoanUser =
	// o2oLoanUserService.findById(newLoanapply.getLoanId(),
	// newLoanapply.getLoanapplyNo());
	// if (!oldLoanUser.getUserFullName().equals(newLoanUser.getUserFullName())
	// || !oldLoanUser.getDocumentNo().equals(newLoanUser.getDocumentNo())) {
	// return BaseRestResult.warn("划拨单号:" + loanapplyExpandForm.getTransferNum()
	// + ",当前借款人身份证和姓名,与上笔贷款借款人姓名和身份证不匹配");
	// }
	// O2OComBackFee comBackFee =
	// o2oComBankFeeService.checkBackStatus(loanapplyEx.getLoanapply_no());
	// if (null != comBackFee && null != comBackFee.getBackDeposite() &&
	// comBackFee.getBackDeposite().compareTo(BigDecimal.ZERO) == 1) {
	// return BaseRestResult.warn("划拨单号:" + loanapplyExpandForm.getTransferNum()
	// + ",正在新系统走退费流程");
	// }
	// // 校验单号是否逾期
	// List<O2oStatus> o2oStatusList =
	// o2oOverdueReportService.findBillCode(loanapplyExpandForm.getTransferNum());
	// if (!o2oStatusList.isEmpty()) {
	// if (!o2oStatusList.isEmpty()) {
	// List<String> strList = new ArrayList<>();
	// for (int j = 0; j < o2oStatusList.size(); j++) {
	// strList.add(o2oStatusList.get(j).getStatus());
	// }
	// if (!strList.contains(StatusContexts.O2O_FIVE)) {
	// return BaseRestResult.warn("划拨单号:" + loanapplyExpandForm.getTransferNum()
	// + ",借款逾期未结清");
	// }
	// }
	// }
	// loanapplyExpandForm.setTransferDeposit(BigDecimalToZero(loanapplyEx.getRedDeposite()).subtract(BigDecimalToZero(loanapplyEx.getRetaDeposite())));
	// loanapplyExpandForm.setTrandepositNo(recSubretnAmount(loanapplyEx.getRedDeposite(),
	// loanapplyEx.getRetaDeposite()));
	// if (loanapplyExpandDetail != null) {
	// loanapplyExpandDetailService.updateExpandId(this.updateExpandDetail(loanapplyExpandDetail,
	// loanapplyExpand, loanapplyExpandForm));
	// } else {
	// loanapplyExpandForm.setReceiveDeposit(subBigDecimal(loanapplyExpand.getRecDeposite(),loanapplyExpandForm.getTransferDeposit()));
	// loanapplyExpandDetailService.save(this.saveExpandDetail(loanapplyExpand,
	// loanapplyExpandForm));
	// }
	// } else {
	// return BaseRestResult.warn("划拨单号不存在");
	// }
	// }
	// }
	// } else {
	// LoanapplyExpandDetail loanapplyExpandDetail =
	// loanapplyExpandDetailService.queryDetail(loanapplyExpand.getId());
	// if (loanapplyExpandDetail != null) {
	// loanapplyExpandDetail.setBillCode(loanapplyExpand.getBillCode());
	// loanapplyExpandDetail.setExpandId(loanapplyExpand.getId());
	// loanapplyExpandDetail.setPaidDeposite(loanapplyExpandForm.getReceiveDeposit());
	// loanapplyExpandDetail.setPaidManger(loanapplyExpandForm.getPaidManger());
	// loanapplyExpandDetail.setPaidRisk(loanapplyExpandForm.getPaidRisk());
	// loanapplyExpandDetail.setPayName(loanapplyExpandForm.getPayName());
	// loanapplyExpandDetail.setPayRemark(loanapplyExpandForm.getPayRemark());
	// loanapplyExpandDetail.setUpdator(userUtil.getUserName());
	// loanapplyExpandDetail.setTransferDeposit(loanapplyExpandForm.getTransferDeposit());
	// loanapplyExpandDetail.setReceiveDeposit(loanapplyExpandForm.getReceiveDeposit());
	// loanapplyExpandDetail.setTransferNum(loanapplyExpandForm.getTransferNum());
	// loanapplyExpandDetail.setSubmitDate(loanapplyExpandForm.getSubmitDate());
	// loanapplyExpandDetailService.updateExpandId(loanapplyExpandDetail);
	// } else {
	// loanapplyExpandDetailService.save(this.saveExpandDetail(loanapplyExpand,
	// loanapplyExpandForm));
	// }
	// }
	// return
	// BaseRestResult.info("保存成功").andJquerySelectAjaxAction("#sqbzj_refresh");
	// }
	/**
	 * 收取保证金和管理费 信贷经理提交
	 * 
	 * @return
	 */
	@RequestMapping("/saveManger")
	public BaseRestResult<String> saveMangerDepsite(LoanapplyExpandForm loanapplyExpandForm) {
		LoanapplyExpand loanapplyExpand = loanapplyExpandService.queryLoanapplyNo(loanapplyExpandForm.getLoanapplyNo());
		if (loanapplyExpandForm.getTransferNums() != null && !loanapplyExpandForm.getTransferNums().isEmpty()) {
			for (int i = 0; i < loanapplyExpandForm.getTransferNums().size(); i++) {
				LoanapplyExpandDetail loanapplyExpandDetail = loanapplyExpandDetailService.queryDetail(loanapplyExpand.getId());
				loanapplyExpandForm.setTransferNum(loanapplyExpandForm.getTransferNums().get(i));
				O2oLoanapplyEntity loanapply = o2oLoanapplyService.findBillCode1(loanapplyExpandForm.getTransferNum());
				if (null == loanapply) {
					return BaseRestResult.warn("划拨单号:" + loanapplyExpandForm.getTransferNum() + "不存在,请核实");
				} else {
					LoanapplyExpand loanapplyEx = loanapplyExpandService.fingByBillCode(loanapplyExpandForm.getTransferNum());
					if (!loanapplyEx.getBillStatus().equals(StatusContexts.BZJ_STATUS_CLO)) {
						return BaseRestResult.warn("划拨单号:" + loanapplyExpandForm.getTransferNum() + "未收取保证金与管理费");
					}
					if (!checkDeposit(loanapplyEx.getRedDeposite(), loanapplyEx.getRetaDeposite(), loanapplyExpandForm.getTransferDeposit())) {
						return BaseRestResult.warn("划拨单号:" + loanapplyExpandForm.getTransferNum() + ",划拨金额超过原单号可退保证金金额");
					}
					O2oLoanapplyEntity oldLoanapply = o2oLoanapplyService.findById(loanapplyEx.getLoanapply_no());
					O2oLoanapplyEntity newLoanapply = o2oLoanapplyService.findById(loanapplyExpandForm.getLoanapplyNo());
					O2oLoanUserEntity oldLoanUser = o2oLoanUserService.findById(oldLoanapply.getLoanId(), oldLoanapply.getLoanapplyNo());
					O2oLoanUserEntity newLoanUser = o2oLoanUserService.findById(newLoanapply.getLoanId(), newLoanapply.getLoanapplyNo());
					if (!oldLoanUser.getUserFullName().equals(newLoanUser.getUserFullName()) || !oldLoanUser.getDocumentNo().equals(newLoanUser.getDocumentNo())) {
						return BaseRestResult.warn("划拨单号:" + loanapplyExpandForm.getTransferNum() + ",当前借款人身份证和姓名,与上笔贷款借款人姓名和身份证不匹配");
					}
					O2OComBackFee comBackFee = o2oComBankFeeService.checkBackStatus(loanapplyEx.getLoanapply_no());
					if (null != comBackFee && null != comBackFee.getBackDeposite() && comBackFee.getBackDeposite().compareTo(BigDecimal.ZERO) == 1) {
						return BaseRestResult.warn("划拨单号:" + loanapplyExpandForm.getTransferNum() + ",系统走退费流程");
					}
					// 校验单号是否逾期
					List<O2oStatus> o2oStatusList = o2oOverdueReportService.findBillCode(loanapplyExpandForm.getTransferNum());
					if (!o2oStatusList.isEmpty()) {
						if (!o2oStatusList.isEmpty()) {
							List<String> strList = new ArrayList<>();
							for (int j = 0; j < o2oStatusList.size(); j++) {
								strList.add(o2oStatusList.get(j).getStatus());
							}
							if (!strList.contains(StatusContexts.O2O_FIVE)) {
								return BaseRestResult.warn("划拨单号:" + loanapplyExpandForm.getTransferNum() + ",借款逾期未结清");
							}
						}
					}
					loanapplyExpandForm.setTransferDeposit(BigDecimalToZero(loanapplyEx.getRedDeposite()).subtract(BigDecimalToZero(loanapplyEx.getRetaDeposite())));
					loanapplyExpandForm.setTrandepositNo(recSubretnAmount(loanapplyEx.getRedDeposite(), loanapplyEx.getRetaDeposite()));
					if (loanapplyExpandDetail != null) {
						loanapplyExpandDetailService.updateExpandId(this.updateExpandDetail(loanapplyExpandDetail, loanapplyExpand, loanapplyExpandForm));
					} else {
						loanapplyExpandForm.setReceiveDeposit(subBigDecimal(loanapplyExpand.getRecDeposite(), loanapplyExpandForm.getTransferDeposit()));
						loanapplyExpandDetailService.save(this.saveExpandDetail(loanapplyExpand, loanapplyExpandForm));
					}
				}
			}
		} else {
			LoanapplyExpandDetail loanapplyExpandDetail = loanapplyExpandDetailService.queryDetail(loanapplyExpand.getId());
			if (loanapplyExpandDetail != null) {
				loanapplyExpandDetail.setBillCode(loanapplyExpand.getBillCode());
				loanapplyExpandDetail.setExpandId(loanapplyExpand.getId());
				loanapplyExpandDetail.setPaidDeposite(loanapplyExpandForm.getReceiveDeposit());
				loanapplyExpandDetail.setPaidManger(loanapplyExpandForm.getPaidManger());
				loanapplyExpandDetail.setPaidRisk(loanapplyExpandForm.getPaidRisk());
				loanapplyExpandDetail.setPayName(loanapplyExpandForm.getPayName());
				loanapplyExpandDetail.setPayRemark(loanapplyExpandForm.getPayRemark());
				loanapplyExpandDetail.setUpdator(userUtil.getUserName());
				loanapplyExpandDetail.setTransferDeposit(loanapplyExpandForm.getTransferDeposit());
				loanapplyExpandDetail.setReceiveDeposit(loanapplyExpandForm.getReceiveDeposit());
				loanapplyExpandDetail.setTransferNum(loanapplyExpandForm.getTransferNum());
				loanapplyExpandDetail.setSubmitDate(loanapplyExpandForm.getSubmitDate());
				loanapplyExpandDetailService.updateExpandId(loanapplyExpandDetail);
			} else {
				loanapplyExpandDetailService.save(this.saveExpandDetail(loanapplyExpand, loanapplyExpandForm));
			}
		}
		return BaseRestResult.info("保存成功").andJquerySelectAjaxAction("#sqbzj_refresh");
	}

	//
	// /**
	// * 保存 保证金和管理费表单 资金查账
	// *
	// * @return
	// */
	// @RequestMapping("/saveDate")
	// public BaseRestResult<String> savePayDate(SQBZJForm sqbjzForm) {
	// LoanapplyExpand loanapplyExpand =
	// loanapplyExpandService.queryLoanapplyNo(sqbjzForm.getLoanapplyNo());
	// LoanapplyExpandDetail loanapplyExpandDetail =
	// loanapplyExpandDetailService.queryDetail(loanapplyExpand.getId());
	// BigDecimal recTotal = null;
	// BigDecimal redTotal =
	// sqbjzForm.getRedDeposite().add(sqbjzForm.getRedManger()).add(sqbjzForm.getRedRisk());
	// if (loanapplyExpandDetail == null) {
	// if (loanapplyExpand.getPaidManger() == null) {
	// recTotal =
	// loanapplyExpand.getRecDeposite().add(loanapplyExpand.getRecManger()).add(loanapplyExpand.getRecRisk());
	// } else {
	// recTotal =
	// loanapplyExpand.getReceiveDeposit().add(loanapplyExpand.getPaidManger()).add(loanapplyExpand.getPaidRisk());
	// }
	// } else {
	// recTotal =
	// loanapplyExpandDetail.getPaidDeposite().add(loanapplyExpandDetail.getPaidManger()).add(loanapplyExpandDetail.getPaidRisk());
	// }
	// if (redTotal.compareTo(recTotal) == -1) {
	// return BaseRestResult.warn("本次到款合计金额不能小于本次打款合计金额");
	// }
	// logger.info("财务资金查账：LoanapplyNo{}，RedDeposite：{},RedManger：{},RedRisk：{}",
	// sqbjzForm.getLoanapplyNo(), sqbjzForm.getRedDeposite(),
	// sqbjzForm.getRedManger(), sqbjzForm.getRedRisk());
	// if (loanapplyExpandDetail != null) {
	// logger.info("资金查账开始校验");
	// if(loanapplyExpandDetail.getTransferNum()!=null){
	// loanapplyExpand.setRedDeposite(loanapplyExpandDetail.getRedDeposite());
	// loanapplyExpand.setRedManger(loanapplyExpandDetail.getRedManger());
	// loanapplyExpand.setRedRisk(loanapplyExpandDetail.getRedRisk());
	// loanapplyExpand.setReceiveDeposit(loanapplyExpandDetail.getReceiveDeposit());
	// loanapplyExpand.setPayDate(loanapplyExpandDetail.getPayDate());
	// loanapplyExpand.setPayName(loanapplyExpandDetail.getPayName());
	// loanapplyExpand.setPaidDeposite(loanapplyExpandDetail.getPaidDeposite());
	// loanapplyExpand.setPaidManger(loanapplyExpandDetail.getPaidManger());
	// loanapplyExpand.setPaidRisk(loanapplyExpandDetail.getPaidRisk());
	// loanapplyExpand.setPayRemark(loanapplyExpandDetail.getPayRemark());
	// loanapplyExpand.setTransferDeposit(loanapplyExpandDetail.getTransferDeposit());
	// loanapplyExpand.setPayDate(loanapplyExpandDetail.getPayDate());
	// loanapplyExpand.setSubmitDate(loanapplyExpandDetail.getSubmitDate());
	// if(loanapplyExpandDetail.getTransferNum().contains(",")){
	// String str[]=loanapplyExpandDetail.getTransferNum().split(",");
	// for (int i = 0; i < str.length; i++){
	// loanapplyExpand.setTransferNum(str[i]);
	// if(loanapplyExpandDetail.getTrandepositNo().contains(",")){
	// String tranStr[]=loanapplyExpandDetail.getTrandepositNo().split(",");
	// for (int j = i; j < tranStr.length;){
	// loanapplyExpand.setTransferDeposit(new BigDecimal(tranStr[j]));
	// System.out.println(new BigDecimal(tranStr[j]));
	// TranferResult result =
	// loanapplyExpandUpdateService.checkBzjStatus(loanapplyExpand);
	// if (!result.getFlag()) {
	// logger.info("划拨单号：[{}],资金查账表单校验失败：[{}],ErrorMsg:[{}]",
	// loanapplyExpand.getTransferNum(),result.getResult(), result.getResult());
	// return BaseRestResult.warn(result.getResult());
	// }
	// break;
	// }
	// }
	// }
	// }else{
	// loanapplyExpand.setTransferNum(loanapplyExpandDetail.getTransferNum());
	// loanapplyExpand.setTransferDeposit(new
	// BigDecimal(loanapplyExpandDetail.getTrandepositNo()));
	// TranferResult result =
	// loanapplyExpandUpdateService.checkBzjStatus(loanapplyExpand);
	// if (!result.getFlag()) {
	// logger.info("划拨单号：[{}],资金查账表单校验失败：[{}],ErrorMsg:[{}]",
	// loanapplyExpand.getTransferNum(),result.getResult(), result.getResult());
	// return BaseRestResult.warn(result.getResult());
	// }
	// }
	// }
	// loanapplyExpandDetail.setRedDeposite(sqbjzForm.getRedDeposite());
	// loanapplyExpandDetail.setReceiveDeposit(sqbjzForm.getRedDeposite());
	// loanapplyExpandDetail.setRedManger(sqbjzForm.getRedManger());
	// loanapplyExpandDetail.setRedRisk(sqbjzForm.getRedRisk());
	// loanapplyExpandDetail.setPayDate(sqbjzForm.getPayDate());
	// loanapplyExpandDetailService.updateExpandId(loanapplyExpandDetail);
	// } else {
	// LoanapplyExpandDetail expandDetail = new LoanapplyExpandDetail();
	// expandDetail.setRedDeposite(sqbjzForm.getRedDeposite());
	// expandDetail.setRedManger(sqbjzForm.getRedManger());
	// expandDetail.setRedRisk(sqbjzForm.getRedRisk());
	// expandDetail.setReceiveDeposit(loanapplyExpand.getReceiveDeposit());
	// expandDetail.setPayDate(sqbjzForm.getPayDate());
	// expandDetail.setPayName(loanapplyExpand.getPayName());
	// if (loanapplyExpand.getPaidManger() != null) {
	// expandDetail.setPaidDeposite(loanapplyExpand.getPaidDeposite() == null ?
	// BigDecimal.ZERO : loanapplyExpand.getPaidDeposite());
	// expandDetail.setPaidManger(loanapplyExpand.getPaidManger() == null ?
	// BigDecimal.ZERO : loanapplyExpand.getPaidManger());
	// expandDetail.setPaidRisk(loanapplyExpand.getPaidRisk() == null ?
	// BigDecimal.ZERO : loanapplyExpand.getPaidRisk());
	// } else {
	// expandDetail.setPaidDeposite(loanapplyExpand.getRecDeposite());
	// expandDetail.setPaidManger(loanapplyExpand.getRecManger());
	// expandDetail.setPaidRisk(loanapplyExpand.getRecRisk());
	// }
	// expandDetail.setPayRemark(loanapplyExpand.getPayRemark());
	// expandDetail.setTransferDeposit(loanapplyExpand.getTransferDeposit());
	// expandDetail.setTransferNum(loanapplyExpand.getTransferNum());
	// expandDetail.setPayDate(sqbjzForm.getPayDate());
	// expandDetail.setExpandId(loanapplyExpand.getId());
	// expandDetail.setBillCode(loanapplyExpand.getBillCode());
	// expandDetail.setSubmitDate(loanapplyExpand.getSubmitDate());
	// loanapplyExpandDetailService.save(expandDetail);
	// }
	// return
	// BaseRestResult.info("保存成功").andJquerySelectAjaxAction("sqbzj_refresh");
	// }
	@RequestMapping("/saveDate")
	public BaseRestResult<String> savePayDate(SQBZJForm sqbjzForm) {

		LoanapplyExpand loanapplyExpand = loanapplyExpandService.queryLoanapplyNo(sqbjzForm.getLoanapplyNo());
		LoanapplyExpandDetail loanapplyExpandDetail = loanapplyExpandDetailService.queryDetail(loanapplyExpand.getId());
		BigDecimal recTotal = null;
		BigDecimal redTotal = sqbjzForm.getRedDeposite().add(sqbjzForm.getRedManger()).add(sqbjzForm.getRedRisk());
		if (loanapplyExpandDetail == null) {
			if (loanapplyExpand.getPaidManger() == null) {
				recTotal = loanapplyExpand.getRecDeposite().add(loanapplyExpand.getRecManger()).add(loanapplyExpand.getRecRisk());
			} else {
				recTotal = loanapplyExpand.getReceiveDeposit().add(loanapplyExpand.getPaidManger()).add(loanapplyExpand.getPaidRisk());
			}
		} else {
			recTotal = loanapplyExpandDetail.getPaidDeposite().add(loanapplyExpandDetail.getPaidManger()).add(loanapplyExpandDetail.getPaidRisk());
		}
		if (redTotal.compareTo(recTotal) == -1) {
			return BaseRestResult.warn("本次到款合计金额不能小于本次打款合计金额");
		}
		logger.info("财务资金查账：LoanapplyNo{}，RedDeposite：{},RedManger：{},RedRisk：{}", sqbjzForm.getLoanapplyNo(), sqbjzForm.getRedDeposite(), sqbjzForm.getRedManger(), sqbjzForm.getRedRisk());
		if (loanapplyExpandDetail != null) {
			logger.info("资金查账开始校验");
			if (loanapplyExpandDetail.getTransferNum() != null) {
				// loanapplyExpand.setRedDeposite(loanapplyExpandDetail.getRedDeposite());
				// loanapplyExpand.setRedManger(loanapplyExpandDetail.getRedManger());
				// loanapplyExpand.setRedRisk(loanapplyExpandDetail.getRedRisk());
				loanapplyExpand.setReceiveDeposit(loanapplyExpandDetail.getReceiveDeposit());
				loanapplyExpand.setPayDate(loanapplyExpandDetail.getPayDate());
				loanapplyExpand.setPayName(loanapplyExpandDetail.getPayName());
				loanapplyExpand.setPaidDeposite(loanapplyExpandDetail.getPaidDeposite());
				loanapplyExpand.setPaidManger(loanapplyExpandDetail.getPaidManger());
				loanapplyExpand.setPaidRisk(loanapplyExpandDetail.getPaidRisk());
				loanapplyExpand.setPayRemark(loanapplyExpandDetail.getPayRemark());
				loanapplyExpand.setTransferDeposit(loanapplyExpandDetail.getTransferDeposit());
				loanapplyExpand.setPayDate(loanapplyExpandDetail.getPayDate());
				loanapplyExpand.setSubmitDate(loanapplyExpandDetail.getSubmitDate());
				if (loanapplyExpandDetail.getTransferNum().contains(",")) {
					String str[] = loanapplyExpandDetail.getTransferNum().split(",");
					for (int i = 0; i < str.length; i++) {
						loanapplyExpand.setTransferNum(str[i]);
						if (loanapplyExpandDetail.getTrandepositNo().contains(",")) {
							String tranStr[] = loanapplyExpandDetail.getTrandepositNo().split(",");
							for (int j = i; j < tranStr.length;) {
								loanapplyExpand.setTransferDeposit(new BigDecimal(tranStr[j]));
								TranferResult result = loanapplyExpandUpdateService.checkBzjStatus(loanapplyExpand);
								if (!result.getFlag()) {
									logger.info("划拨单号：[{}],资金查账表单校验失败：[{}],ErrorMsg:[{}]", loanapplyExpand.getTransferNum(), result.getResult(), result.getResult());
									return BaseRestResult.warn(result.getResult());
								}
								break;
							}
						}
					}
				} else {
					loanapplyExpand.setTransferNum(loanapplyExpandDetail.getTransferNum());
					loanapplyExpand.setTransferDeposit(new BigDecimal(loanapplyExpandDetail.getTrandepositNo()));
					TranferResult result = loanapplyExpandUpdateService.checkBzjStatus(loanapplyExpand);
					if (!result.getFlag()) {
						logger.info("划拨单号：[{}],资金查账表单校验失败：[{}],ErrorMsg:[{}]", loanapplyExpand.getTransferNum(), result.getResult(), result.getResult());
						return BaseRestResult.warn(result.getResult());
					}
				}
			}
			loanapplyExpandDetail.setRedDeposite(sqbjzForm.getRedDeposite());
			loanapplyExpandDetail.setReceiveDeposit(sqbjzForm.getRedDeposite());
			loanapplyExpandDetail.setRedManger(sqbjzForm.getRedManger());
			loanapplyExpandDetail.setRedRisk(sqbjzForm.getRedRisk());
			loanapplyExpandDetail.setPayDate(sqbjzForm.getPayDate());
			logger.info("临时表更新loanapplyExpand主表：RedDeposite{}RedManger:{}RedRisk:{}", loanapplyExpand.getRedDeposite(), loanapplyExpand.getRedManger(), loanapplyExpand.getRedRisk());
			loanapplyExpandDetailService.updateExpandId(loanapplyExpandDetail);
			loanapplyExpand.setSkBankAccount(sqbjzForm.getSkBankAccount());
			loanapplyExpandService.updateById(loanapplyExpand);
		} else {
			LoanapplyExpandDetail expandDetail = new LoanapplyExpandDetail();
			expandDetail.setRedDeposite(sqbjzForm.getRedDeposite());
			expandDetail.setRedManger(sqbjzForm.getRedManger());
			expandDetail.setRedRisk(sqbjzForm.getRedRisk());
			expandDetail.setReceiveDeposit(loanapplyExpand.getReceiveDeposit());
			expandDetail.setPayDate(sqbjzForm.getPayDate());
			expandDetail.setPayName(loanapplyExpand.getPayName());
			if (loanapplyExpand.getPaidManger() != null) {
				expandDetail.setPaidDeposite(loanapplyExpand.getPaidDeposite() == null ? BigDecimal.ZERO : loanapplyExpand.getPaidDeposite());
				expandDetail.setPaidManger(loanapplyExpand.getPaidManger() == null ? BigDecimal.ZERO : loanapplyExpand.getPaidManger());
				expandDetail.setPaidRisk(loanapplyExpand.getPaidRisk() == null ? BigDecimal.ZERO : loanapplyExpand.getPaidRisk());
			} else {
				expandDetail.setPaidDeposite(loanapplyExpand.getRecDeposite());
				expandDetail.setPaidManger(loanapplyExpand.getRecManger());
				expandDetail.setPaidRisk(loanapplyExpand.getRecRisk());
			}
			expandDetail.setPayRemark(loanapplyExpand.getPayRemark());
			expandDetail.setTransferDeposit(loanapplyExpand.getTransferDeposit());
			expandDetail.setTransferNum(loanapplyExpand.getTransferNum());
			expandDetail.setPayDate(sqbjzForm.getPayDate());
			expandDetail.setExpandId(loanapplyExpand.getId());
			expandDetail.setBillCode(loanapplyExpand.getBillCode());
			expandDetail.setSubmitDate(loanapplyExpand.getSubmitDate());
			logger.info("临时表保存，更新loanapplyExpand主表：RedDeposite{}RedManger:{}RedRisk:{}", loanapplyExpand.getRedDeposite(), loanapplyExpand.getRedManger(), loanapplyExpand.getRedRisk());
			loanapplyExpandDetailService.save(expandDetail);
			loanapplyExpand.setSkBankAccount(sqbjzForm.getSkBankAccount());
			loanapplyExpandService.updateById(loanapplyExpand);
		}
		return BaseRestResult.info("保存成功").andJquerySelectAjaxAction("sqbzj_refresh");
	}

	/**
	 * 重新划拨保证金
	 * 
	 * @param expandId
	 * @return
	 */
	@RequestMapping("/restart")
	public BaseRestResult<String> deleteLoanapplyExpandDetail(String id) {
		loanapplyExpandDetailService.delete(id);
		return BaseRestResult.info("重新划拨成功").andJquerySelectAjaxAction("#sqbzj_refresh");
	}

	/**
	 * @Description: <p>
	 *               个人账户退款，动态表单
	 *               </p>
	 * @author yy
	 * @date 2017年12月05日 上午11:03:11
	 * @version V1.0
	 */
	@RequestMapping("/savegrtf_account")
	public BaseRestResult<String> savegrtf_account(String id, String backSjNo, String backDate) {
		if (StringUtil.isBlank(backSjNo)) {
			return BaseRestResult.warn("请选择实际退费账户!");
		}
		if (StringUtil.isBlank(backDate)) {
			return BaseRestResult.warn("实际退款时间!");
		}
		User user = UserHolder.getUser();
		O2oBackFeesEntity o2oBackFees = o2oBackFeesService.queryById(id);
		o2oBackFees.setBackSjNo(backSjNo);
		try {
			o2oBackFees.setBackDate(DateUtils.parseDate(backDate, "yyyy-MM-dd"));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		o2oBackFees.setUpdateId(user.getNo());
		o2oBackFees.setUpdateName(user.getCname());
		o2oBackFees.setUpdateDate(new Date());
		int i = o2oBackFeesService.update(o2oBackFees);
		if (i > 0) {
			return BaseRestResult.info("保存成功");
		} else {
			return BaseRestResult.warn("保存失败");
		}
	}

	/**
	 * @Description: <p>
	 *               退保证金管理费资金部门付款节点动态表单展示 选择付款账号保存
	 *               </p>
	 * @author CXW
	 * @date 2017年8月25日 上午11:03:11
	 * @version V1.0
	 */
	@RequestMapping("/savetf_account")
	public BaseRestResult<String> savetf_account(String id, String tkBankAccount) {
		if (StringUtil.isBlank(tkBankAccount)) {
			return BaseRestResult.warn("请选择实际退费账户!");
		}
		LoanapplyExpand loanapplyExpand = loanapplyExpandService.getById(id);
		loanapplyExpand.setTkBankAccount(tkBankAccount);
		int i = loanapplyExpandService.updateById(loanapplyExpand);
		if (i > 0) {
			return BaseRestResult.info("保存成功");
		} else {
			return BaseRestResult.warn("保存失败");
		}
	}

	/**
	 * 保存 退费保证金和管理费表单 财务审批
	 * 
	 * @return
	 */
	@RequestMapping("/saveDateTf")
	public BaseRestResult<String> savePayDateTf(TFBZJForm tfbjzForm) {
		O2OComBackFee o2OComBackFee = o2oComBankFeeService.queryById(tfbjzForm.getId());
		o2OComBackFee.setPayDate(com.eascs.common.util.DateUtils.formateStandDate(tfbjzForm.getPayDate()));
		o2oComBankFeeService.updateById(o2OComBackFee);
		return BaseRestResult.warn("保存成功");
	}

	/**
	 * 面签申报合同是否齐备
	 * 
	 * @param zXPTCWForm
	 * @return
	 */
	@RequestMapping("/updateContranctFlag")
	public BaseRestResult<String> interviewUp(MQFrom mqFrom) {
		o2oLoanapplyService.updateContractFlag(mqFrom);
		return BaseRestResult.warn("保存成功");
	}

	/**
	 * 更新客户银行卡信息
	 * 
	 * @param zXPTCWForm
	 * @return
	 */
	@RequestMapping("/bank_update")
	public BaseRestResult<String> interviewUp(ContractAndBankInfoForm o2oBankInfoForm, String flag) {
		O2oLoanapplyEntity o2oloanapply = o2oLoanapplyService.findById(o2oBankInfoForm.getLoanapplyno());
		o2oloanapply.setReceiveBank(o2oBankInfoForm.getBankZhiName());
		o2oloanapply.setBankAccount(o2oBankInfoForm.getBankCardNo());
		o2oLoanapplyService.updateO2oBankInfoEntity(o2oloanapply);
		return BaseRestResult.info("保存成功").andRefresh();
	}

	/**
	 * 银行放款--申报
	 * 
	 * @param yhssForm
	 * @return
	 */
	@RequestMapping("/payment")
	public BaseRestResult<String> payment(YHSSForm yhssForm) throws Exception {
		O2oLoanapplyEntity o2oloanapply = o2oLoanapplyService.findById(yhssForm.getLoanapplyNo());
		O2oLoanUserEntity loanUser = o2oLoanUserService.findById(o2oloanapply.getLoanId(), yhssForm.getLoanapplyNo());
//		O2oBankLoanData bankLoanData = o2oLoanServiceImpl.queryBillCode(o2oloanapply.getBillCode());
		if (!(yhssForm.getEaMount().compareTo(o2oloanapply.getEaMount()) == 0)) {
			return BaseRestResult.warn("放款金额跟EA批复金额不一致，不能保存！");
		}
		if (Integer.valueOf(yhssForm.getLoanTerm()) != o2oloanapply.getLoanTerm()) {
			return BaseRestResult.warn("还款期限跟内部审批申请期限不一致，不能保存！");
		}
		if (!yhssForm.getBankLoanName().equals(o2oloanapply.getBankLoanName())){
			return BaseRestResult.warn("放款银行跟内部送审银行不一致，不能保存！");
		}
		O2oLoanForm o2oloanForm = new O2oLoanForm();
		o2oloanForm.setBillCode(o2oloanapply.getBillCode());
		o2oloanForm.setApplyAmount(o2oloanapply.getLoanaMount());
		o2oloanForm.setLoanAmount(yhssForm.getEaMount());
		o2oloanForm.setLoanRate(o2oloanapply.getLoanrate());
		o2oloanForm.setLoanerCard(loanUser.getDocumentNo());
		// o2oloanForm.setLoanBankCode(o2oloanapply.getBankLoanName());
		o2oloanForm.setLoanBankCode(yhssForm.getBankLoanName());
		o2oloanForm.setLoanTerm(Integer.valueOf(yhssForm.getLoanTerm()));
		o2oloanForm.setLoanerName(loanUser.getUserFullName());
		o2oloanForm.setLoanDate(yhssForm.getPaymentTime());
		o2oloanForm.setDataType("2");
		o2oloanapply.setPaymentTime(DateUtils.parseDate(yhssForm.getPaymentTime(), new String[] { "yyyy-MM-dd" }));
		o2oloanapply.setBankAmount(yhssForm.getEaMount());
		o2oloanapply.setInstrumentNumber(yhssForm.getInstrumentNumber());
		o2oloanapply.setWfType(StatusContexts.O2O_FK_END);
		o2oloanapply.setLoanFlg(StatusContexts.O2O_YES);
		// 修改放款银行，不会修改到内审送审银行
		// o2oloanapply.setBankLoanName(yhssForm.getBankLoanName());
		O2oUpdateLoanExpireTimeEntity updateLoanTime = new O2oUpdateLoanExpireTimeEntity();
		updateLoanTime.setLoanapplyNo(o2oloanapply.getLoanapplyNo());
		updateLoanTime.setLoanTime(com.eascs.common.util.DateUtils.formateStandDate(o2oloanForm.getLoanDate()));
		updateLoanTime.setTerm(o2oloanForm.getLoanTerm());
		updateLoanTime.setExpireTime();
		o2oloanapply.setEndBankDate(new java.sql.Date(updateLoanTime.getExpireTime().getTime()));
		// start
		O2oLoanapplyEntity o2oloan = o2oLoanapplyService.findById(yhssForm.getLoanapplyNo());
		o2oloan.setWfType(o2oloan.getWfType());
		// end
		workFlowSumbitService.updatePayment(o2oloanapply, o2oloanForm);
		if (!StatusContexts.O2O_FK_END.equals(o2oloan.getWfType()))
			declareSignService.timer(o2oloanapply, yhssForm.getBankLoanName());
		return BaseRestResult.info("保存成功").andJquerySelectAjaxAction("#file_uploader");
	}

	@Autowired
	O2oFinanceFlowService o2oFinanceFlowService;
	@Autowired
	O2oCancleServiceImpl o2oCancleServiceImpl;

	/**
	 * 作废按钮
	 * 
	 * @return
	 */
	@RequestMapping("/invalidLoanLapply")
	public BaseRestResult<String> invalidLoanLapply(O2oCacleEntity payform) {
		com.eascs.admin.common.vo.ModelResult<Boolean> r = o2oCancleServiceImpl.worlFlowCancle(payform);
		if (r.isSuccess()) {
			return BaseRestResult.info("作废成功").andRefresh();
		} else {
			logger.info("作废单号：[{}]失败, message:[{}]", payform.getLoanapplyNo(), r.getErrMsg());
			return BaseRestResult.warn("作废失败").andRefresh();
		}
	}

	/**
	 * @Description: <p>
	 *               作废公共调用workflow接口
	 *               </p>
	 * @author CXW
	 * @date 2017年6月8日 下午2:02:00
	 * @version V1.0
	 */
	public ModelResult<Boolean> cancelProcess(O2oLoanapplyEntity loan, CancleProcessParam cancleProcessParam, O2oCacleEntity cacleEntity) {
		ModelResult<Boolean> model = workFlowService.cancelProcess(cancleProcessParam);
		if (model.isSuccess()) {
			if (!StatusContexts.WFTYPE_FINANCE.equals(cacleEntity.gettType())) {
				loan.setWfType(StatusContexts.O2O_FK_OVER);
				loan.setEndDate(new Date());
				loan.setEndRo(userUtil.getUpdateOr());
				O2oLoanapplyEntity loanapply = o2oLoanapplyService.findById(loan.getLoanapplyNo());
				o2oLoanapplyService.updateEntityById(loan);
				saveLog(loanapply, loan, cacleEntity.gettRemark());
			}
			// 更新作废记录表状态
			cacleEntity.settIsSuccess(StatusContexts.O2O_YES);
			o2oCancleServiceImpl.updateCalcle(cacleEntity);
			logger.info("工作流关闭单号为：{} 流程成功", loan.getLoanapplyNo());
		} else {
			logger.info("工作流关闭单号为：{} 流程失败", loan.getLoanapplyNo());
		}
		return model;
	}

	/**
	 * 作废-记录到操作日志表
	 * 
	 * @param loanapply
	 * @param loan
	 */
	public void saveLog(O2oLoanapplyEntity loanapply, O2oLoanapplyEntity loan, String reMark) {
		// 对象转json
		ObjectMapper mapper = new ObjectMapper();
		try {
			// 记录到操作日志表
			o2oLoanapplyService.saveLog(UserHolder.getUser().getCname(), O2oLogType.LOAN_STATUS_T, mapper.writeValueAsString(loanapply), mapper.writeValueAsString(loan));
			// 记录到【结清操作记录】和【作废操作记录】 日志表
			o2oRecordLogService.saveLog(loan.getBillCode(), UserHolder.getUser().getCname(), O2oLogType.LOAN_STATUS_T, loan.getEndDate(), reMark, "录入");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 还款完成 按钮
	 * 
	 * @param loanapplyNo
	 * @return
	 */
	@RequestMapping("/repayment")
	public BaseRestResult<String> repay(String loanapplyNo) {

		ViewContext.put("loanapplyNo", loanapplyNo);

		return HtmlRestResult.popHtmlFragment("detail/repay");

	}

	// 贷后查询--贷款详情--还款完成
	@RequestMapping("/repaymentOver")
	public BaseRestResult<String> repaymentOver(String loanapplyNo, String settleDate) {
		if (StringUtil.isEmpty(settleDate)) {
			return BaseRestResult.warn("请选择结清日期");
		}
		AccountEntity accountEntity = o2oChargeSituationService.queryLoanAccount(loanapplyNo, "311");
		if (null == accountEntity || null == accountEntity.getBalance() || accountEntity.getBalance().compareTo(BigDecimal.ZERO) == 0 ) {
			return BaseRestResult.warn("账务系统未收到保证金，不能结清！");
		}
		o2oLoanapplyService.updateWorkFlowStatus(StatusContexts.O2O_REPAY_END, loanapplyNo);
		O2oLoanapplyEntity loanEntity = o2oLoanapplyService.findById(loanapplyNo);
		loanEntity.setSettleDate(com.eascs.common.util.DateUtils.formateStandDate(settleDate));
		o2oLoanapplyService.updateEntityById(loanEntity);
		try {
			// 记录到操作日志表
			/*
			 * o2oLoanapplyService.saveLog(UserHolder.getUser().getCname(),
			 * "HN", null,
			 * "借款单号为："+loanEntity.getBillCode()+",结清日期是："+settleDate);
			 */
			o2oLoanapplyService.saveLog(UserHolder.getUser().getCname(), O2oLogType.LOAN_STATUS_HN, "贷款详情--还款完成", "借款单号为：" + loanEntity.getBillCode() + ",结清日期是：" + settleDate);
			// 记录到【结清操作记录】和【作废操作记录】 日志表
			o2oRecordLogService.saveLog(loanEntity.getBillCode(), UserHolder.getUser().getCname(), O2oLogType.LOAN_STATUS_HN, loanEntity.getSettleDate(), loanEntity.getRemark(), "录入");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return BaseRestResult.info("提交成功").andRefresh();
	}

	/**
	 * 面签申报 送报银行
	 * 
	 * @param loanapplyNo
	 * @return
	 */
	@RequestMapping("/save_bankLoanData")
	public BaseRestResult<String> checkBankLoanData(MQZBSBYHFrom mQZBSBYHFrom) {
		O2oLoanapplyEntity o2oloanapply = o2oLoanapplyService.findById(mQZBSBYHFrom.getReferId());
		if (StringUtil.isNotBlank(mQZBSBYHFrom.getIsCheckMqCl())) {
			o2oloanapply.setIsCheckMqCl(mQZBSBYHFrom.getIsCheckMqCl());
		} else {
			return BaseRestResult.warn("确认信息不能为空");// .andRefresh();
		}

		o2oLoanapplyService.updateEntityById(o2oloanapply);
		return BaseRestResult.info("保存成功");// .andRefresh();
	}

	/**
	 * 面签申报 是否代偿
	 * 
	 * @param loanapplyNo
	 * @return
	 */
	@RequestMapping("/saveDcFlag")
	public BaseRestResult<String> checkBankLoanData_phone(MQSCForm mqScform) {
		logger.info("面签申报审查节点代偿表单VO：mqScform:[{}]", mqScform.toString());
		O2oLoanapplyEntity o2oloanapply = o2oLoanapplyService.findById(mqScform.getLoanapplyNo());
		o2oloanapply.setIsDcflag(mqScform.getIsDcflag());
		o2oloanapply.setDcRemark(mqScform.getDcRemark());
		o2oLoanapplyService.updateEntityById(o2oloanapply);
		return BaseRestResult.info("保存成功");
	}

	/**
	 * 面签申报 申报审核电核
	 * 
	 * @param mQZBSBYHFrom
	 * @return
	 */
	@RequestMapping("/save_bankLoanData_phone")
	public BaseRestResult<String> checkBankLoanData_phone(MQZBSBYHFrom mQZBSBYHFrom) {
		O2oLoanapplyEntity o2oloanapply = o2oLoanapplyService.findById(mQZBSBYHFrom.getReferId());
		if (StringUtil.isNotBlank(mQZBSBYHFrom.getIsPhoneCheck())) {
			o2oloanapply.setIsPhoneCheck(mQZBSBYHFrom.getIsPhoneCheck());
		} else {
			return BaseRestResult.warn("请选择是否电核");
		}

		if (StringUtil.isNotBlank(mQZBSBYHFrom.getPhoneCheckMessage())) {
			o2oloanapply.setPhoneCheckMessage(mQZBSBYHFrom.getPhoneCheckMessage());
		} else {
			return BaseRestResult.warn("电核反馈意见不能为空");
		}
		o2oLoanapplyService.updateEntityById(o2oloanapply);
		return BaseRestResult.info("保存成功");
	}

	/**
	 * 校验是否大于保证金
	 * 
	 * @param recDeposit
	 * @param retnDeposit
	 * @return
	 */
	public boolean checkDeposit(BigDecimal recDeposit, BigDecimal retnDeposit, BigDecimal transferDeposit) {
		boolean flag = true;
		BigDecimal amount = recDeposit.subtract(null == retnDeposit ? BigDecimal.ZERO : retnDeposit);
		if (amount.compareTo(BigDecimal.ZERO) == -1) {
			flag = false;
		}
		return flag;
	}

	/**
	 * 更新临时表
	 * 
	 * @param loanapplyExpandDetail
	 * @param loanapplyExpand
	 * @param loanapplyExpandForm
	 * @return
	 */
	private LoanapplyExpandDetail updateExpandDetail(LoanapplyExpandDetail loanapplyExpandDetail, LoanapplyExpand loanapplyExpand, LoanapplyExpandForm loanapplyExpandForm) {
		loanapplyExpandDetail.setBillCode(loanapplyExpand.getBillCode());
		loanapplyExpandDetail.setExpandId(loanapplyExpand.getId());
		loanapplyExpandDetail.setPaidDeposite(subBigDecimal(loanapplyExpandDetail.getPaidDeposite(), loanapplyExpandForm.getTransferDeposit()));
		loanapplyExpandDetail.setPaidManger(loanapplyExpandForm.getPaidManger());
		loanapplyExpandDetail.setPaidRisk(loanapplyExpandForm.getPaidRisk());
		loanapplyExpandDetail.setPayName(loanapplyExpandForm.getPayName());
		loanapplyExpandDetail.setPayRemark(loanapplyExpandForm.getPayRemark());
		loanapplyExpandDetail.setUpdator(userUtil.getUserName());
		loanapplyExpandDetail.setTransferDeposit(BigDecimalToZero(loanapplyExpandDetail.getTransferDeposit()).add(BigDecimalToZero(loanapplyExpandForm.getTransferDeposit())));
		loanapplyExpandDetail.setReceiveDeposit(loanapplyExpandDetail.getPaidDeposite());
		loanapplyExpandDetail.setTransferNum(StringUtils.isNotBlank(loanapplyExpandDetail.getTransferNum()) ? (loanapplyExpandDetail.getTransferNum() + "," + loanapplyExpandForm.getTransferNum()) : loanapplyExpandForm.getTransferNum());
		loanapplyExpandDetail.setSubmitDate(loanapplyExpandForm.getSubmitDate());
		loanapplyExpandDetail.setTrandepositNo(StringUtils.isNotBlank(loanapplyExpandDetail.getTrandepositNo()) ? (loanapplyExpandDetail.getTrandepositNo() + "," + loanapplyExpandForm.getTrandepositNo()) : loanapplyExpandForm.getTrandepositNo());
		loanapplyExpandForm.setReceiveDeposit(loanapplyExpandDetail.getPaidDeposite());
		return loanapplyExpandDetail;
	}

	/**
	 * 保存临时表
	 * 
	 * @param loanapplyExpandDetail
	 * @param loanapplyExpand
	 * @param loanapplyExpandForm
	 * @return
	 */
	private LoanapplyExpandDetail saveExpandDetail(LoanapplyExpand loanapplyExpand, LoanapplyExpandForm loanapplyExpandForm) {

		LoanapplyExpandDetail loanapplyExpandDetail1 = new LoanapplyExpandDetail();
		loanapplyExpandDetail1.setExpandId(loanapplyExpand.getId());
		loanapplyExpandDetail1.setBillCode(loanapplyExpand.getBillCode());
		loanapplyExpandDetail1.setPaidDeposite(loanapplyExpandForm.getReceiveDeposit());
		loanapplyExpandForm.setReceiveDeposit(loanapplyExpandDetail1.getPaidDeposite());
		loanapplyExpandDetail1.setPaidManger(loanapplyExpandForm.getPaidManger());
		loanapplyExpandDetail1.setPaidRisk(loanapplyExpandForm.getPaidRisk());
		loanapplyExpandDetail1.setPayName(loanapplyExpandForm.getPayName());
		loanapplyExpandDetail1.setPayRemark(loanapplyExpandForm.getPayRemark());
		loanapplyExpandDetail1.setUpdator(userUtil.getUserName());
		loanapplyExpandDetail1.setTransferDeposit(loanapplyExpandForm.getTransferDeposit());
		loanapplyExpandDetail1.setReceiveDeposit(loanapplyExpandForm.getReceiveDeposit());
		loanapplyExpandDetail1.setTrandepositNo(loanapplyExpandForm.getTrandepositNo());
		loanapplyExpandDetail1.setTransferNum(loanapplyExpandForm.getTransferNum());
		loanapplyExpandDetail1.setSubmitDate(loanapplyExpandForm.getSubmitDate());
		return loanapplyExpandDetail1;
	}

	/**
	 * BigDecimal空值处理
	 * 
	 * @return
	 */
	private BigDecimal BigDecimalToZero(BigDecimal decimal) {
		if (decimal == null) {
			decimal = BigDecimal.ZERO;
		}
		if (decimal.compareTo(BigDecimal.ZERO) == -1) {
			decimal = BigDecimal.ZERO;
		}
		return decimal;
	}

	/**
	 * BigDecimal 减法操作
	 * 
	 * @param paidDeposit
	 * @param reciveDeposit
	 * @return
	 */
	private BigDecimal subBigDecimal(BigDecimal paidDeposit, BigDecimal reciveDeposit) {
		BigDecimal decimal = BigDecimal.ZERO;
		if (paidDeposit == null)
			paidDeposit = BigDecimal.ZERO;
		if (reciveDeposit == null)
			reciveDeposit = BigDecimal.ZERO;
		decimal = paidDeposit.subtract(reciveDeposit);
		if (decimal.compareTo(BigDecimal.ZERO) == -1)
			decimal = BigDecimal.ZERO;
		return decimal;
	}

	/**
	 * 计算每笔划拨保证金 金额
	 * 
	 * @param recDeposit
	 * @param retnDeposit
	 * @return
	 */
	private String recSubretnAmount(BigDecimal recDeposit, BigDecimal retnDeposit) {
		if (recDeposit == null) {
			recDeposit = BigDecimal.ZERO;
		}
		if (retnDeposit == null) {
			retnDeposit = BigDecimal.ZERO;
		}
		return String.valueOf(recDeposit.subtract(retnDeposit));
	}

	/**
	 * 特殊面签申报 特殊面签申报原因
	 * 
	 * @param mQZBSBYHFrom
	 * @return
	 */
	@RequestMapping("/save_bankLoanData_tsmqsb")
	public BaseRestResult<String> checkBankLoanData_tsmqsb(MQZBSBYHFrom mQZBSBYHFrom) { // 就用电核的那个message吧
		O2OSpecialInterview specialInterview = o2OSpecialInterviewService.queryEntity(mQZBSBYHFrom.getReferId());
		if (StringUtil.isNotBlank(mQZBSBYHFrom.getPhoneCheckMessage())) {
			if (mQZBSBYHFrom.getPhoneCheckMessage().length() > StatusContexts.O2O_TSMQSB_MESSAGE_SIZE) {
				return BaseRestResult.warn("特殊面签申报原因不能超过2000");
			}
			specialInterview.setSpecialReasons(mQZBSBYHFrom.getPhoneCheckMessage());
		} else {
			return BaseRestResult.warn("特殊面签申报原因不能为空");
		}

		o2OSpecialInterviewService.update(specialInterview);
		return BaseRestResult.info("保存成功");
	}

	/**
	 * 征信归档凭证保存
	 * 
	 * @param zXPTCWForm
	 * @return
	 */
	@RequestMapping("/credit_save")
	public BaseRestResult<String> creditSave(MQFrom mqFrom) {
		o2oLoanapplyService.updateContractFlag(mqFrom);
		return BaseRestResult.warn("保存成功");
	}

	/**
	 * @Title: collectFees_form
	 * @Description:个人账户动态表单保存
	 * @author 张庆奇
	 * @param vo
	 * @return
	 * @throws ParseException
	 * @return BaseRestResult<String>
	 * @throws
	 * @date 2017年12月7日 上午9:52:38
	 */
	@RequestMapping(value = "/collectFees_form")
	public BaseRestResult<String> collectFees_form(O2oCollectFeesVo vo) throws ParseException {
		if (vo.getCollectDate() == null) {
			return BaseRestResult.warn("到账时间不能为空！");
		}
		if (StringUtil.isBlank(vo.getCollectNo())) {
			return BaseRestResult.warn("请选择收款账户!");
		}
		if (StringUtil.isBlank(vo.getNoYes())) {/////////////////////////////////
			return BaseRestResult.warn("请选择是否已到账！");
		}
		User user = UserHolder.getUser();
		O2oCollectFee o2oCollectFee = io2oCollectFeesService.queryById(vo.getId());
		o2oCollectFee.setCollectNo(vo.getCollectNo());
		o2oCollectFee.setCollectDate(DateUtils.parseDate(vo.getCollectDate(), "yyyy-MM-dd"));
		o2oCollectFee.setUpdateId(user.getNo());
		o2oCollectFee.setUpdateName(user.getCname());
		o2oCollectFee.setUpdateDate(new Date());
		o2oCollectFee.setNoYes(vo.getNoYes());////////////////////
		io2oCollectFeesService.update(o2oCollectFee);
		return BaseRestResult.warn("操作成功");
	}
	/**
	 * 中行附件接口发送按钮更新状态
	 * 
	 * @return
	 */
	@RequestMapping("/confirmupdatebcfiletypeButton")
	public BaseRestResult<String> reloan(String loanapplyNo) {
		return BaseRestResult.confirm("确定发送中行申报文件?").andActionAjaxLoad("/workflowsubmit/updatebcfiletypeButton?loanapplyNo=" + loanapplyNo );
	}
	@RequestMapping("/updatebcfiletypeButton")
	public BaseRestResult<String> updatebcfiletypeButton(String loanapplyNo) {
		O2oLoanapplyEntity entity = o2oLoanapplyService.findById(loanapplyNo);
		entity.setBankfiletype("Y");
		o2oLoanapplyService.updateEntityById(entity);
		return BaseRestResult.info("发送状态更新成功").andJquerySelectAjaxAction("#file_type_Button");
	}
}
